package com.ruoyi.query;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.query.entity.Query;
import com.ruoyi.query.service.QueryService;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * **********************
 * * Author: XiaShiLong *
 * * Date  : 2021-04-17 *
 * * Time  : 09:08      *
 * * to    : lz&xm      *
 * **********************
 * 查询缓存
 **/
public class QueryUtils {

    private final static String REDIS_KEY = "query_condition:redis_";

    /**
     * 设置缓存
     *
     * @param key       参数键
     * @param queryList 查询集合
     */
    public static void setCache(String key, List<Query> queryList) {
        SpringUtils.getBean(RedisCache.class).setCacheList(key, queryList);
    }

    /**
     * 获取缓存(用户)
     */
    public static List<Query> getCacheUser(Long menuId, String className) {
        String key = key(className, SecurityUtils.getUserId());
        List<Query> cacheObj = SpringUtils.getBean(RedisCache.class).getCacheList(key);
        if (StringUtils.isNotEmpty(cacheObj)) {
            return cacheObj;
        } else {
            List<Query> list = SpringUtils.getBean(QueryService.class).getByMenuIdAndUserId(menuId);
            if (StringUtils.isNotEmpty(list)) {
                setCache(key, list);
                return list;
            }
        }
        return Collections.emptyList();
    }

    public static List<Query> getCacheUserAll(Long menuId, String className) {
        List<Query> list = new ArrayList<>();
        Collection<String> keys = SpringUtils.getBean(RedisCache.class).keys(userKeys(className));
        keys.forEach(
                key -> {
                    List<Query> cacheObj = SpringUtils.getBean(RedisCache.class).getCacheList(key);
                    if (StringUtils.isNotEmpty(cacheObj)) {
                        list.addAll(cacheObj);
                    } else {
                        list.addAll(SpringUtils.getBean(QueryService.class).getByMenuIdAndType(menuId, 1));
                    }
                }
        );
        return list;
    }

    /**
     * 获取缓存(管理员)
     */
    public static List<Query> getCacheAdmin(Long menuId, String className) {
        String key = adminKey(className);
        List<Query> cacheObj = SpringUtils.getBean(RedisCache.class).getCacheList(key);
        if (StringUtils.isNotEmpty(cacheObj)) {
            return cacheObj;
        } else {
            List<Query> list = SpringUtils.getBean(QueryService.class).getByMenuIdAndType(menuId, 0);
            if (StringUtils.isNotEmpty(list)) {
                setCache(key, list);
                return list;
            }
        }
        return Collections.emptyList();
    }

    public static void deleteCaChe(String key) {
        SpringUtils.getBean(RedisCache.class).deleteObject(key);
    }

    public static void deleteCaCheUserAll(String className) {
        Collection<String> keys = SpringUtils.getBean(RedisCache.class).keys(userKeys(className));
        keys.forEach(QueryUtils::deleteCaChe);
    }

    /**
     * 更新用户
     */
    public static void updateUser(Query query) {
        removeUser(query);
        setCache(key(query.getClassPath(), SecurityUtils.getUserId()), Collections.singletonList(query));
    }

    /**
     * 更新管理员
     */
    public static void updateAdmin(Query query) {
        removeAdmin(query);
        setCache(adminKey(query.getClassPath()), Collections.singletonList(query));
    }


    /**
     * 用户删除
     */
    public static void removeUser(Query query) {
        remove(key(query.getClassPath(), SecurityUtils.getUserId()), getCacheUser(query.getMenuId(), query.getClassPath()), query);
    }

    /**
     * 删除管理员
     */
    public static void removeAdmin(Query query) {
        remove(adminKey(query.getClassPath()), getCacheAdmin(query.getMenuId(), query.getClassPath()), query);
    }

    /**
     * 删除后保存到缓存
     *
     * @param key       缓存key
     * @param queryList 目标集合
     * @param delete    待删除对象
     */
    private static void remove(String key, List<Query> queryList, Query delete) {
        if (null != queryList && !queryList.isEmpty()) {
            queryList.removeIf(query -> query.getId().equals(delete.getId()));
            if (queryList.isEmpty()) {
                deleteCaChe(key);
            } else {
                setCache(key, queryList);
            }
        }
    }

    /**
     * 生成redis key
     *
     * @param className 类名
     * @param userId    用户id
     * @return String key
     */
    public static String key(String className, Long userId) {
        return REDIS_KEY + className + "_user_" + userId;
    }

    /**
     * 获取全体用户key
     *
     * @param className 类名
     * @return String
     */
    public static String userKeys(String className) {
        return REDIS_KEY + className + "_user_" + "*";
    }

    /**
     * 管理员生成redis key
     *
     * @param className 类名
     * @return String key
     */
    public static String adminKey(String className) {
        return REDIS_KEY + className + "_ADMIN";
    }
}
